import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/bean/novel_search.dart';
import 'package:flutter_bsbdj/data_base/novel_table.dart';
import 'package:flutter_bsbdj/pagers/ebook/novel_detail.dart';
import 'package:flutter_bsbdj/utils/widget_views.dart';
import 'package:flutter_bsbdj/utils/http_util.dart';
import 'package:dio/dio.dart';

class SearchResult extends StatefulWidget {
  String name;

  SearchResult(this.name);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ResultWidget();
  }
}

class ResultWidget extends State<SearchResult> {
  NovelSearch _novelSearch;
  bool _showAllDesc = false;
  List<Relate> _relateList;
  FirstChapter first_chapter;
  LatestChapter latest_chapter;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getSearchNovel();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.name),
      ),
      body: _novelSearch == null
          ? Container(
              child: WidgetViews.getInstance().loading(),
            )
          : ListView(
              children: <Widget>[
                Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      _mainInfo(_novelSearch.data.aladdin),
                    ],
                  ),
                ),
                Column(
                  children: _relateWidgetList(),
                )
              ],
            ),
    );
  }

  //上部详情
  Widget _mainInfo(Result result) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.all(5),
      padding: EdgeInsets.all(5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            height: 110,
            child: Row(
              children: <Widget>[
                Container(
                  width: 80,
                  margin: EdgeInsets.only(right: 10),
                  child: WidgetViews.getInstance().cachedImage(result.cover,
                      function: () {
                    if (first_chapter != null) {
                      _openBook(result, first_chapter.cid, true);
                    }
                  }),
                ),
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      result.title,
                      style: TextStyle(
                          fontSize: 15,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold),
                    )),
                    Expanded(
                        child: Row(
                      children: <Widget>[
                        Text(
                          "${result.author}   ",
                          style: TextStyle(color: Colors.grey, fontSize: 12),
                        ),
                        Text(
                          result.category,
                          style:
                              TextStyle(color: Colors.deepOrange, fontSize: 12),
                        )
                      ],
                    )),
                    Expanded(
                        child: Text(
                      result.tags,
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                    )),
                    Expanded(
                        child: Text(
                      "热度:${result.hh_hot}",
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                    )),
                    first_chapter == null
                        ? Container()
                        : Expanded(
                            child: GestureDetector(
                            child: Text(
                              first_chapter.cname,
                              style: TextStyle(
                                  color: Colors.blueAccent, fontSize: 12),
                            ),
                            onTap: () {
                              _openBook(result, first_chapter.cid, false);
                            },
                          )),
                    latest_chapter == null
                        ? Container()
                        : Expanded(
                            child: GestureDetector(
                            child: Text(
                              latest_chapter.cname,
                              style:
                                  TextStyle(color: Colors.green, fontSize: 12),
                            ),
                            onTap: () {
                              _openBook(result, latest_chapter.cid, false);
                            },
                          )),
                  ],
                ))
              ],
            ),
          ),
          result.desc.length <= 50
              ? Text(result.desc)
              : Container(
                  child: Stack(
                    alignment: Alignment.bottomRight,
                    children: <Widget>[
                      Container(
                        child: _showAllDesc
                            ? Text(result.desc)
                            : Text(result.desc.substring(0, 50)),
                        padding: EdgeInsets.only(bottom: 20),
                      ),
                      GestureDetector(
                        child: Container(
                          color: Color(0x00000000),
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(right: 5, bottom: 5),
                          height: 20,
                          child: Icon(
                            _showAllDesc
                                ? Icons.keyboard_arrow_up
                                : Icons.keyboard_arrow_down,
                            color: Colors.grey,
                          ),
                        ),
                        onTap: () {
                          setState(() {
                            _showAllDesc = !_showAllDesc;
                          });
                        },
                      ),
                    ],
                  ),
                ),
        ],
      ),
    );
  }

  //相关书籍列表item集合
  List<Widget> _relateWidgetList() {
    List<Widget> wids = [];
    if (_relateList == null || _relateList.length == 0) {
      return wids;
    }
    for (var relate in _relateList) {
      wids.add(_relateItem(relate));
    }
    return wids;
  }

  //相关书籍列表item
  Widget _relateItem(Relate relate) {
    return GestureDetector(
      child: Container(
        color: Colors.white,
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.all(5),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              height: 100,
              child: Row(
                children: <Widget>[
                  Container(
                    width: 80,
                    margin: EdgeInsets.only(right: 10),
                    child: WidgetViews.getInstance().cachedImage(relate.cover,
                        function: () {
                      if (first_chapter != null) {
                        _openRelate(relate, true);
                      }
                    }),
                  ),
                  Expanded(
                      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                          child: Text(
                        relate.title,
                        style: TextStyle(
                            fontSize: 15,
                            color: Colors.black54,
                            fontWeight: FontWeight.bold),
                      )),
                      Expanded(
                          child: Row(
                        children: <Widget>[
                          Text(
                            "${relate.author}   ",
                            style: TextStyle(color: Colors.grey, fontSize: 12),
                          ),
                          Text(
                            relate.category,
                            style: TextStyle(
                                color: Colors.deepOrange, fontSize: 12),
                          )
                        ],
                      )),
                      Expanded(
                          child: Text(
                        relate.tags,
                        style: TextStyle(color: Colors.grey, fontSize: 12),
                      )),
                      Expanded(
                          child: Text(
                        "热度:${relate.hh_hot}",
                        style: TextStyle(color: Colors.grey, fontSize: 12),
                      )),
                      Expanded(
                          child: GestureDetector(
                        child: Text(
                          relate.first_chapter,
                          style:
                              TextStyle(color: Colors.blueAccent, fontSize: 12),
                        ),
                        onTap: () {
                          _openRelate(relate, true);
                        },
                      )),
                    ],
                  ))
                ],
              ),
            ),
            relate.desc.length <= 45
                ? Text(relate.desc)
                : Text(relate.desc.substring(0, 45)),
          ],
        ),
      ),
      onTap: () {
        _openRelate(relate, true);
      },
    );
  }

  //相关书打开
  void _openRelate(Relate result, bool lastReader) {
    _insertData(
        result.authorid.toString(),
        result.author,
        result.title,
        result.bid.toString(),
        result.first_cid.toString(),
        result.cover,
        result.category,
        result.desc);
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => NovelReader(result.title, result.bid.toString(),
            result.first_cid.toString(), lastReader)));
  }

  //搜索书打开
  void _openBook(Result result, String cid, bool lastReader) {
    _insertData(result.authorid.toString(), result.author, result.title,
        result.bid.toString(), cid, result.cover, result.category, result.desc);
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) =>
            NovelReader(result.title, result.bid.toString(), cid, lastReader)));
  }

  void _insertData(
      String author,
      String author_name,
      String bookname,
      String bid,
      String cid,
      String book_cover,
      String class_name,
      String book_info) async {
    var t = await NovelTable.getInstance()
        .insertBook(
            0,
            author,
            author_name,
            bookname,
            bid,
            cid,
            book_cover,
            class_name,
            book_info.length > 25
                ? book_info.substring(0, 25).replaceAll("\n", "")
                : book_info.replaceAll("\n", ""))
        .then((value) {});
  }

  void _getSearchNovel() async {
    FormData formData = FormData();
    formData.add("name", widget.name);
    await HttpUtil.getInstance()
        .post("novelInfoApi", data: formData)
        .then((value) {
      try {
        NovelSearch search = NovelSearch.fromJson(value.data);
        setState(() {
          _novelSearch = search;
          first_chapter = _novelSearch.data.aladdin.first_chapter;
          latest_chapter = _novelSearch.data.aladdin.latest_chapter;
          _relateList = _novelSearch.data.data;
        });
      } catch (e) {}
    });
  }
}
